import { Button, Col, Menu, message, Row, Space, Spin } from 'antd';
import { connect } from 'umi';
import '../common/styles.less';
import { useEffect, useRef, useState } from 'react';
import MyIcon from '@/components/MyIcon';
import { CenterFormView } from './CenterFormView';
import { PersonalCenterAPI } from '../common/type';
import { modifyPwdService, modifySelfService, reloadSelfInfoService } from '../services';
import { getUserID } from '@/utils';
import { TipTextModal } from '@/components/TipsErrorModal';

const CenterView: React.FC<PersonalCenterAPI.ICenterView> = ({ curRes }) => {
  const prefixCls = 'centerview-';

  const centerFormRef = useRef<PersonalCenterAPI.IUpdateLeftColFormRef>(null); //右侧表单ref

  /**
   * 保存当前选中菜单 key
   */
  const [menuSelectKey, setMenuSelectKey] = useState<string[]>(['dataSettings']);

  /**
   * 提示框
   */
  const [errorTipModal, setErrorTiModal] = useState<any>({
    showTipModal: false,
    tipText: '',
  });

  /**
   * 菜单选中改变
   * @param menuKey 点击菜单的key
   */
  const onMenuClick = (menuKey: string) => {
    setMenuSelectKey([menuKey]);
  };

  /**
   * 引入用户详情接口
   */
  const { reloadSelfInfoLoading, reloadSelfInfoObj, reloadSelfInfoRun } = reloadSelfInfoService();

  useEffect(() => {
    let payload = {
      id: getUserID(),
    };
    reloadSelfInfoRun(payload);
  }, [curRes]);

  /**
   * 刷新详情
   */
  const reloadDetailInfo = () => {
    let payload = {
      id: getUserID(),
    };
    reloadSelfInfoRun(payload);
  };

  /**
   * 引入修改密码
   */
  const { modifyPwdLoading, modifyPwdRun } = modifyPwdService();

  /**
   * 修改个人信息接口回调
   * @param res 接口返回数据
   */
  const modifySelfCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      let payload = {
        id: getUserID(),
      };
      reloadSelfInfoRun(payload);
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入修改资料接口
   */
  const { modifySelfLoading, modifySelfRun } = modifySelfService(modifySelfCallback);

  /**
   * 个人中心保存
   */
  const saveOkCenter = () => {
    if (menuSelectKey && menuSelectKey?.toString() == 'dataSettings') {
      centerFormRef?.current?.centerBasicForm?.validateFields()?.then((values: any) => {
        let selfPayload: any = {
          ...values,
          id: getUserID(),
          versionNum: reloadSelfInfoObj?.versionNum,
        };
        modifySelfRun(selfPayload);
      });
    } else if (menuSelectKey && menuSelectKey?.toString() == 'changePassword') {
      centerFormRef?.current?.centerPasswordForm?.validateFields()?.then((values: any) => {
        if (values?.newPwd == values?.pwd) {
          let tipState = {
            showTipModal: true,
            tipText: '原密码不能和新密码一致，请重新设置！',
          };
          setErrorTiModal(tipState);
        } else {
          if (values?.newPwd == values?.confirmPwd) {
            let modifyObj: any = {
              pwd: values?.pwd,
              newPwd: values?.newPwd,
              id: getUserID(),
              versionNum: reloadSelfInfoObj?.versionNum,
            };
            modifyPwdRun(modifyObj);
          } else {
            let tipState = {
              showTipModal: true,
              tipText: '新密码和确认密码不一致，请重新设置！',
            };
            setErrorTiModal(tipState);
          }
        }
      });
    }
  };

  // 个人中心左侧菜单  V4.24.8
  const leftMenuItems = [
    {
      label: (
        <>
          <MyIcon type="icon-pandian1" style={{ marginRight: '.5rem' }} />
          资料设置
        </>
      ),
      key: 'dataSettings',
    },
    // 暂时不启用
    // {
    //   label: (
    //     <>
    //       <MyIcon type="icon-lock" style={{ marginRight: '.5rem' }} />
    //       更改密码
    //     </>
    //   ),
    //   key: 'changePassword',
    // },
  ];

  return (
    <>
      <div className={prefixCls + 'divBox'}>
        <Spin spinning={reloadSelfInfoLoading || modifyPwdLoading || modifySelfLoading} wrapperClassName={prefixCls + 'centerSpin'}>
          <Row className={prefixCls + 'centerViewRow'}>
            <Col span={4} style={{ borderRight: '1px dashed #cdcdcd' }}>
              <div className={prefixCls + 'centerMenu'}>
                <Menu
                  onClick={(e) => {
                    onMenuClick(e?.key);
                  }}
                  selectedKeys={menuSelectKey}
                  items={leftMenuItems}
                />
              </div>
            </Col>
            <Col span={20} className={prefixCls + 'centerViewRow-Col'}>
              <div className={prefixCls + 'rightFormStyle'} style={{ padding: '2rem 0px 0px 2rem' }}>
                <CenterFormView ref={centerFormRef} menuSelectKey={menuSelectKey} userInfoObj={reloadSelfInfoObj} reloadDetailInfo={reloadDetailInfo} />
              </div>
              {/* 暂时不启用 */}
              {/* <div className={prefixCls + 'centerViewRow-Col-btn'}>
                <Space>
                  <Button onClick={saveOkCenter} type={'primary'}>
                    保存
                  </Button>
                </Space>
              </div> */}
            </Col>
          </Row>
        </Spin>
      </div>
      {/* 错误提示 */}
      {errorTipModal?.showTipModal && (
        <TipTextModal
          onClose={() => {
            let tipState = {
              showTipModal: false,
              tipText: '',
            };
            setErrorTiModal(tipState);
          }}
          configTestRes={errorTipModal?.tipText}
        />
      )}
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(CenterView);
